﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.SessionState;
using org.pdfbox.pdmodel;
using org.pdfbox.util;
using log4net;

/// <summary>
/// Summary description for Upload
/// </summary>
public class Upload:IHttpHandler, IRequiresSessionState
{
    protected ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
	public Upload()
	{
		//
		// TODO: Add constructor logic here
		//
	}


    #region IHttpHandler Members

    public bool IsReusable
    {
        get { return true; }
    }

    public void ProcessRequest(HttpContext context)
    {
        string UserName = "";
        if (context.Session["UserName"] != null)
        {
             UserName = context.Session["UserName"].ToString();
        }
        string parentFolder = "/Uploads/Resumes/OldCV/" + getFolderName(context);
        string uploadPath = context.Server.MapPath(parentFolder);
        string pathDB = parentFolder + "/";
        DatabaseHelper DB = new DatabaseHelper();
        //;context.Server.MapPath(context.Request.ApplicationPath + "/Upload");
        // loop through all the uploaded files
        for (int j = 0; j < context.Request.Files.Count; j++)
        {
            // get the current file
            HttpPostedFile uploadFile = context.Request.Files[j];
            // if there was a file uploded
            if (uploadFile.ContentLength > 0)
            {
                string result = DB.ExecuteScalar("CheckFileExists N'" + uploadFile.FileName+"'").ToString();
                if (result != "1")
                {
                    uploadFile.SaveAs(Path.Combine(uploadPath, uploadFile.FileName));
                    ReadFile(Path.Combine(uploadPath, uploadFile.FileName), pathDB + uploadFile.FileName, UserName);
                }
                else
                {
                    log.Info("-------------------------------------------- ");
                    log.Info("File nay da ton tai " + uploadFile.FileName);
                }
            }
        }
        context.Response.Write("");
    }

    #endregion

#region Process file pdf

    private string getFolderName(HttpContext context)
    {
        string Result = "";
        string folder = context.Server.MapPath("/Uploads/Resumes/OldCV");
        string[] subdirEntries = Directory.GetDirectories(folder);
        foreach (string subdir in subdirEntries)
        {
            string[] filePaths = Directory.GetFiles(subdir);
            if (filePaths.Length <= 500)
            {
                int index = subdir.LastIndexOf("\\");
                string folderName = subdir.Substring(index + 1);
                return Result = folderName;
            }
        }
        return Result;
    }

    private void ReadFile(string pathFile,string pathDB,string UserName)
    {
        try
        {
            //string pathFile = Server.MapPath("/" + "Uploads/Resumes/CV/Dang_Phuong_Anh.pdf");
            PDDocument doc = PDDocument.load(pathFile);
            //PDDocument doc = PDDocument.load(pathFile);
            PDFTextStripper pdfStripper = new PDFTextStripper();
            string chuoi = pdfStripper.getText(doc);

            if (chuoi.IndexOf("TÓM LƯỢC") != -1 && chuoi.IndexOf("KINH NGHIỆM LÀM VIỆC") != -1)
            {
                ReadInfo(chuoi, pathDB, UserName);
            }
            else
            {
                ReadInfo2(chuoi, pathDB, UserName);
            }

        }
        catch (Exception ex)
        {
            log.Info("-------------------------------------------- ");
            log.Error("File khong insert duoc " + pathFile);
            log.Error(ex.ToString());
        }
    }

    public void ReadInfo2(string chuoi, string pathFile, string UserName)
    {
        string Query = "";
        string tomluoc = "";
        string kynang = "";
        string thamkhao = "";
        // Lấy vị trí từng ký tự đặc biệt.
        int ViTriThongTinCaNhan = chuoi.IndexOf("THÔNG TIN CÁ NHÂN");
        int ViTriThongTinChung = -1;
        if (chuoi.IndexOf("THÔNG TIN CHUNG") != -1)
        {
            ViTriThongTinChung = chuoi.IndexOf("THÔNG TIN CHUNG");
        }
        else
        {
            ViTriThongTinChung = chuoi.IndexOf("TÓM LƯỢC");
        }
        int ViTriMucTieuNgheNghiep = -1;
        if (chuoi.IndexOf("HỒ SƠ") != -1)
        {
            ViTriMucTieuNgheNghiep = chuoi.IndexOf("HỒ SƠ");
        }
        else
        {
            ViTriMucTieuNgheNghiep = chuoi.IndexOf("MỤC TIÊU NGHỀ NGHIỆP");
        }
        // Lấy chuỗi theo từng tiêu đề.        
        string thongtincanhan = chuoi.Substring(ViTriThongTinCaNhan + 20, ViTriThongTinChung - ViTriThongTinCaNhan - 1 - 21).Trim();
        string thongtinchung = chuoi.Substring(ViTriThongTinChung, ViTriMucTieuNgheNghiep - ViTriThongTinChung).Trim();
        thongtinchung = thongtinchung.Replace("THÔNG TIN CHUNG", "");
        thongtinchung = thongtinchung.Replace("HỒ SƠ", "");
        thongtinchung = thongtinchung.Replace("TÓM LƯỢC", "");
        //Lay tong nam kinh nghiem
        //kinhnghiemlamviec = kinhnghiemlamviec.Replace("Tổng số năm kinh nghiệm ", "");
        //int khoangtrang = kinhnghiemlamviec.IndexOf(" ");
        //string duration = kinhnghiemlamviec.Substring(0, khoangtrang).Trim();
        //string descriptionExperient = kinhnghiemlamviec.Replace(duration.ToString() + " năm. \r\n", ""); ;
        //End
        string duration = "0";
        try
        {

            //lblTest.Text = kinhnghiemlamviec;
            DatabaseHelper DB = new DatabaseHelper();
            Query = "Resume_ResumeOldInsert N'" + ReplaceStr(thongtincanhan) + "',N'" + ReplaceStr(thongtinchung) + "',N'" + ReplaceStr("") + "',N'" + ReplaceStr(tomluoc) + "',N'" + ReplaceStr(kynang) + "',N'" + ReplaceStr(thamkhao) + "','" + UserName + "'," + duration + ",N'" + pathFile + "'";
           // log.Info(Query);
            DB.ExecuteNonQuery(Query);
        }
        catch (Exception)
        {
            log.Info("-------------------------------------------- ");
            log.Error("File khong insert duoc " + pathFile);
            log.Info(Query);

        }
    }

    public void ReadInfo(string chuoi, string pathFile, string UserName)
    {
        string Query = "";
        int chieudaichuoi = chuoi.Length;
        // Lấy vị trí từng ký tự đặc biệt.
        int ViTriThongTinCaNhan = chuoi.IndexOf("THÔNG TIN CÁ NHÂN");
        int ViTriTomLuoc = chuoi.IndexOf("TÓM LƯỢC");
        int ViTriKinhNghiemLamViec = chuoi.IndexOf("KINH NGHIỆM LÀM VIỆC");
        int ViTriHocVan = chuoi.IndexOf("HỌC VẤN");
        int ViTriKyNang = chuoi.IndexOf("KỸ NĂNG");
        int ViTriThamKhao = chuoi.IndexOf("THAM KHẢO");
       
        // Lấy chuỗi theo từng tiêu đề.        
        string thongtincanhan = chuoi.Substring(ViTriThongTinCaNhan + 20, ViTriTomLuoc - ViTriThongTinCaNhan - 1 - 21).Trim();
        string tomluoc = chuoi.Substring(ViTriTomLuoc + 10, ViTriKinhNghiemLamViec - ViTriTomLuoc - 1 - 11).Trim();
        string kinhnghiemlamviec = chuoi.Substring(ViTriKinhNghiemLamViec + 22, ViTriHocVan - ViTriKinhNghiemLamViec - 1 - 23).Trim().Trim();

        //Lay tong nam kinh nghiem
        kinhnghiemlamviec = kinhnghiemlamviec.Replace("Tổng số năm kinh nghiệm ", "");
        int khoangtrang = kinhnghiemlamviec.IndexOf(" ");
        string duration = kinhnghiemlamviec.Substring(0, khoangtrang).Trim();
        string descriptionExperient = kinhnghiemlamviec.Replace(duration.ToString() + " năm. \r\n", ""); ;
        //End
        string hocvan = "";
        string kynang = "";
        string thamkhao = "";
        if (ViTriKyNang != -1)
        {
            hocvan = chuoi.Substring(ViTriHocVan + 10, ViTriKyNang - ViTriHocVan - 1 - 11).Trim();
            if (ViTriThamKhao != -1)
            {
                kynang = chuoi.Substring(ViTriKyNang + 10, ViTriThamKhao - 1 - ViTriKyNang - 11).Trim();
                thamkhao = chuoi.Substring(ViTriThamKhao + 12, chieudaichuoi - 1 - ViTriThamKhao - 21).Trim();
            }
            else
            {
                kynang = chuoi.Substring(ViTriKyNang + 10, chieudaichuoi - 1 - ViTriKyNang - 11).Trim();
            }
        }
        else
        {
            hocvan = chuoi.Substring(ViTriHocVan + 10, chieudaichuoi - 1 - ViTriHocVan - 11).Trim();
        }

        try
        {

            //lblTest.Text = kinhnghiemlamviec;
             DatabaseHelper DB = new DatabaseHelper();
             Query = "Resume_ResumeOldInsert N'" + ReplaceStr(thongtincanhan) + "',N'" + ReplaceStr(hocvan) + "',N'" + ReplaceStr(descriptionExperient) + "',N'" + ReplaceStr(tomluoc) + "',N'" + ReplaceStr(kynang) + "',N'" + ReplaceStr(thamkhao) + "','" + UserName + "'," + duration + ",N'" + pathFile + "'";
             DB.ExecuteNonQuery(Query);
        }
        catch (Exception)
        {
            log.Info("-------------------------------------------- ");
            log.Error("File khong insert duoc " + pathFile);
            log.Info(Query);

        }
    }

    private string ReplaceStr(string str)
    {
        string result = "";
        result = ReplacePage(str.Trim());
        result = result.Replace("  ", " ");
        result = result.Replace("'","''");
        result = result.Replace("Resume Detail    ", "");
        result = result.Replace("        By www.vietnamworks.com.vn", "");
        result = result.Replace("Resume Detail                                   By www.vietnamworks.com.vn", "");
        result = result.Replace("\r\n"," ");
        return result.Trim();
    }

    private string ReplacePage(string str)
    {

        string result = str;
        string page = "";

        for (int i = 1; i < 6; i++)
        {
            for (int j = 1; j < 6; j++)
            {
                page = i.ToString() + " / " + j.ToString();
                result = result.Replace(page, "");
            }
        }
        return result.Trim();
    }
    
#endregion
}